﻿using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;

namespace UDS.Web.UI.Controls
{
    /// <summary>
    /// Represents a input(type="button") HTML element. And if clicked, it will redirect the current page to <see cref="RedirectUrl"/>.
    /// </summary>
    public class RedirectButton : WebControl
    {
        /// <summary>
        /// Specify the url to redirect after clicked.
        /// </summary>
        [PersistenceMode(PersistenceMode.Attribute)]
        public string RedirectUrl
        {
            get;
            set;
        }

        /// <summary>
        /// Gets or sets the text to display on the button.
        /// </summary>
        [PersistenceMode(PersistenceMode.Attribute)]
        public string Text
        {
            get;
            set;
        }

        protected override HtmlTextWriterTag TagKey
        {
            get { return HtmlTextWriterTag.Input; }
        }

        protected override void AddAttributesToRender(HtmlTextWriter writer)
        {
            writer.AddAttribute(HtmlTextWriterAttribute.Type, "button");
            writer.AddAttribute(HtmlTextWriterAttribute.Value, Text);

            if (!string.IsNullOrEmpty(RedirectUrl))
            {
                string url = ResolveClientUrl(RedirectUrl);
                string onclickScript = HttpUtil.MergeScript(
                    Attributes["onclick"],
                    string.Format("window.location.href = '{0}';", HttpUtility.HtmlAttributeEncode(url)));

                Attributes.Remove("onclick");
                writer.AddAttribute("onclick", onclickScript);
            }
            base.AddAttributesToRender(writer);
        }
    }
}
